<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			table{
				width:400px;
				margin: 0 auto;
			}
			th{
				background-color: #BDBDBD;
			}
			th,td{
				line-height: 40px;
			}
			a{
				text-decoration: none;
			}
			table,th,td{
				border: 1px solid black;
				text-align: center;
				/* 合并相邻的边框 */
				border-collapse: collapse;
			}
			.head{
				width: 320px;
				margin: 0 auto;
			}
			.head input{
				width: 60px;
			}
		</style>
	</head>
	<body>
		<div class='head'>
			按照价格查询：<input type="text" name="" id="start" value="" />-
			<input type="text" name="" id="end" value="" />
			<button id="search_price">搜索</button>
			<br>
			商品名称查询：<input type="text" name="" id="goods" value="" />
			<button id="search_goods">查询</button>
		</div>
		<table cellspacing="0">
			<thead>
				<tr>
					<th>id</th>
					<th>产品名称</th>
					<th>价格</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
		<script>
			var data = [{
				id: 1,
				name: '小米',
				price: 1000,
			}, {
				id: 2,
				name: 'vivo',
				price: 3000,
			}, {
				id: 3,
				name: '华为',
				price: 2000,
			}, {
				id: 4,
				name: 'apple',
				price: 4000,
			}];
			var tbody = document.querySelector('tbody');
			var search_price = document.querySelector('#search_price');
			var start = document.querySelector('#start');
			var end = document.querySelector('#end');
			var goods = document.querySelector('#goods');
			var search_goods = document.querySelector('#search_goods');
			setData(data);

			function setData(mydata) {
				// 先清空原来tbody里面的数据，在渲染新的数据
				tbody.innerHTML = ''
				mydata.forEach(function(value) {
					var tr = document.createElement('tr');
					tr.innerHTML = '<td>' + value.id + '</td><td>' + value.name + '</td><td>' + value.price + '</td>';
					tbody.appendChild(tr);
				});
			}
			search_price.addEventListener('click', function() {
				var newData = data.filter(function(value) {
					return value.price >= start.value && value.price <= end.value;
				});
				console.log(newData);
				setData(newData); //把拿到的数据渲染到页面中
			});
			search_goods.addEventListener('click', function() {
				var arr = [];
				// some查找数组中是否有满足条件的元素，如果找到为true，则终止循环,执行效率更高		
				data.some(function(value) {
					if (value.name === goods.value) {
						arr.push(value);
						return true; //return后面必须写true
					}
				})
				setData(arr); //把拿到的数据渲染到页面中
			})
		</script>
	</body>
</html>
